/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System.Collections.Generic;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Windows.Controls;
using System.Text;
using System;
using System.Globalization;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    /// <summary>
    /// Interaction logic for PageLogin.xaml
    /// </summary>
    public partial class PagePayGradeImp : PageImpBaseClass
    {
        DbLinkedTextBox wageRateTextBox;
        DbLinkedTextBox rateOnVOvertimePayTextBox;
        DbLinkedCheckBox isEligibleForOtCheckBox;
        DbLinkedTextBox configNameTextBox;

        Label salaryLabel;

        ComboBox comboBoxName;

        /// <summary>
        /// Constructor
        /// </summary>
        public PagePayGradeImp(UIElementCollection stackpanChild, DbLinkedTextBox wageRateTextBox,
            DbLinkedTextBox rateOnOvertimePayTextBox, DbLinkedCheckBox isEligibleForOtCheckBox, 
            DbLinkedCheckBox isSalariedCheckbox, Label salaryLabel, DbLinkedTextBox configNameTextBox,
            ComboBox comboBoxName, GroupBox mainGroup)
        {
            this.ButtonNumber = "3";
            this.ButtonLabelText = "Pay Grades";

            mNewGroupIsDisabled = true;
            mDeleteGroupIsDisabled = true;
            mButtonNewEntityName = "New Pay Grade";
            mButtonDeleteEntityName = "Delete Pay Grade";
            RegisterSaveMeGroupBoxes(null, mainGroup);
            this.wageRateTextBox = wageRateTextBox;
            this.rateOnVOvertimePayTextBox = rateOnOvertimePayTextBox;
            this.comboBoxName = comboBoxName;
            this.isEligibleForOtCheckBox = isEligibleForOtCheckBox;
            this.salaryLabel = salaryLabel;
            this.configNameTextBox = configNameTextBox;

            ///Register the controls and lock the form.
            RegisterUiElementsList(stackpanChild);

            ///Add all text boxes to the list.
            mTextBoxesList.Add(wageRateTextBox);
            mTextBoxesList.Add(rateOnOvertimePayTextBox);
            mTextBoxesList.Add(configNameTextBox);

            isSalariedCheckbox.Checked += new System.Windows.RoutedEventHandler(isSalariedCheckbox_Checked);
            isSalariedCheckbox.Unchecked += new System.Windows.RoutedEventHandler(isSalariedCheckbox_Unchecked);
            ///Add the comboboxes.
            ListofComboboxes.Add(comboBoxName);

            mEntityAddDeleteLoggingEnabled = true;
        }

        override public void Navigating()
        {
            Context.Refresh(RefreshMode.StoreWins, Context.PAYGRADES);
            base.Navigating();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void isSalariedCheckbox_Unchecked(object sender, System.Windows.RoutedEventArgs e)
        {
            PAYGRADE selected = comboBoxName.SelectedItem as PAYGRADE;
            if (selected != null)
            {
                selected.BreaksArePaid = false;
                salaryLabel.Content = "*Rate:";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void isSalariedCheckbox_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            PAYGRADE selected = comboBoxName.SelectedItem as PAYGRADE;
            if (selected != null)
            {
                selected.BreaksArePaid = true;
                salaryLabel.Content = "*Salary:";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        override public List<EntityObject> GetEntityObjectSet()
        {
            return new List<EntityObject>(Context.PAYGRADES.Where(a=>a.Name != null && !a.Name.Contains("Training")).OrderBy(o=>o.Name).ToList());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject GetSelectedEntityObject()
        {
            PAYGRADE selected = comboBoxName.SelectedItem as PAYGRADE;
            return selected;
        }

        /// <summary>
        /// 
        /// </summary>
        public override void MarkEntityDeleted()
        {
            PAYGRADE selected = comboBoxName.SelectedItem as PAYGRADE;
            selected.IsDeleted = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="source"></param>
        public override void UpdateUsersEntitySource()
        {
            ///Create the query object.
            var query = from PAYGRADE in Context.PAYGRADES 
                        where PAYGRADE.IsDeleted == false &&
                        PAYGRADE.Name != null &&
                        !PAYGRADE.Name.Contains("Training")
                        orderby PAYGRADE.WageRate select PAYGRADE;

            if (query.Any())
            {
                List<PAYGRADE> list = query.OrderBy(o => o.Name).ToList();
                comboBoxName.ItemsSource = list;
                if (list != null && list.Count != 0)
                {
                    comboBoxName.SelectedItem = list.First();
                }
                else
                {
                    comboBoxName.ItemsSource = null;
                }
            }
            else
            {
                comboBoxName.ItemsSource = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override EntityObject AddNewEntityObject()
        {
            PAYGRADE newObject = null;
            var q = from PAYGRADE in Context.PAYGRADES where PAYGRADE.Name != null && PAYGRADE.Name.Equals("Not Assigned") select PAYGRADE;

            if (q.Count() == 0)
            {
                newObject = new PAYGRADE();
                newObject.TipTaxRate = 0M;
                newObject.WageRate = 0M;
                newObject.Name = "Not Assigned";
                Context.PAYGRADES.AddObject(newObject);
            }
            else
            {
                newObject = q.First();
                if (newObject.IsDeleted)
                {
                    newObject.IsDeleted = false;
                }
            }
            return newObject;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ComboBox GetEntityComboBox()
        {
            return comboBoxName;
        }


        public override bool SaveMe()
        {
            List<PAYGRADE> databasePaygrades;
            ///First pull a fresh copy of the data from the DB
            using (DominicaEntities newContext = new DominicaEntities(DominicaEntities.GetEfConString()))
            {
                databasePaygrades = newContext.PAYGRADES.ToList();
            }
            ///If any of the paygrades change, we need to mark the old one as deleted and make
            ///a new one.  We then need to update all roles that use that paygrade to point
            ///to the new ID.
            if (databasePaygrades != null && databasePaygrades.Count != 0)
            {
                foreach (PAYGRADE dbpaygrade in databasePaygrades)
                {
                    bool isModified = false;

                    PAYGRADE localPaygrade = Context.PAYGRADES.Where(p => p.Id == dbpaygrade.Id).FirstOrDefault();
                    

                    if (localPaygrade != null)
                    {
                        if (localPaygrade.BreaksArePaid != dbpaygrade.BreaksArePaid)
                        {
                            isModified = true;
                        }
                        else if (localPaygrade.IsEligibleForOvertimePay != dbpaygrade.IsEligibleForOvertimePay)
                        {
                            isModified = true;
                        }
                        else if (localPaygrade.IsSalaried != dbpaygrade.IsSalaried)
                        {
                            isModified = true;
                        }
                        else if (!String.IsNullOrEmpty(localPaygrade.Name) &&
                            !String.IsNullOrEmpty(dbpaygrade.Name)
                            && !localPaygrade.Name.Equals(dbpaygrade.Name))
                        {
                            isModified = true;
                        }
                        else if (localPaygrade.OTAppliedByDayHours != dbpaygrade.OTAppliedByDayHours)
                        {
                            isModified = true;
                        }
                        else if (localPaygrade.OTHoursThreshold != dbpaygrade.OTHoursThreshold)
                        {
                            isModified = true;
                        }
                        else if (localPaygrade.TipTaxRate != dbpaygrade.TipTaxRate)
                        {
                            isModified = true;
                        }
                        else if (localPaygrade.WageRate != dbpaygrade.WageRate)
                        {
                            isModified = true;
                        }
                        else if (localPaygrade.WageRateOnOverTime != dbpaygrade.WageRateOnOverTime)
                        {
                            isModified = true;
                        }

                        ///If the object was modified we need to make a new object with the same values,
                        ///change the old one back to the way it was and 
                        ///and mark it as deleted so it is only used for historical data.
                        if (isModified)
                        {
                            ///Create a new paygrade object, set its values to the values for the
                            ///object that was just changed, then add it to the database.
                            PAYGRADE newObject = new PAYGRADE();
                            SetPayValues(localPaygrade, newObject);
                            Context.PAYGRADES.AddObject(newObject);

                            ///Reset the original objects values, mark it as deleted and
                            ///save.
                            SetPayValues(dbpaygrade, localPaygrade);
                            localPaygrade.IsDeleted = true;
                            Context.SaveChanges();

                            ///Now update all roles to use the new paygrade object.
                            var rolesThatNeedUpdated = Context.ROLES.Where(r => r.PAYGRADE.Id == localPaygrade.Id);
                            if (rolesThatNeedUpdated.Any())
                            {
                                foreach (ROLE role in rolesThatNeedUpdated)
                                {
                                    role.PAYGRADE = newObject;
                                }
                                Context.SaveChanges();
                            }
                        }
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// Copy the values from one paygrade object to another.
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        private static void SetPayValues(PAYGRADE from, PAYGRADE to)
        {
            to.BreaksArePaid = from.BreaksArePaid;
            to.IsEligibleForOvertimePay = from.IsEligibleForOvertimePay;
            to.IsSalaried = from.IsSalaried;
            to.Name = from.Name;
            to.OTAppliedByDayHours = from.OTAppliedByDayHours;
            to.OTHoursThreshold = from.OTHoursThreshold;
            to.TipTaxRate = from.TipTaxRate;
            to.WageRate = from.WageRate;
            to.WageRateOnOverTime = from.WageRateOnOverTime;
        }

        /// <summary>
        /// Assure that the user has entered all of the required data.
        /// </summary>
        public override bool VerifyFormEntries()
        {
            ///Note that even though the form is returning true when it is not verified, that simply means that we
            ///are adding our own custom message and dont want the caller to send an extra message.
            if (base.VerifyFormEntries())
            {
                if (!isEligibleForOtCheckBox.IsChecked.Value)
                {
                    try
                    {
                        Decimal.Parse(wageRateTextBox.Text, NumberStyles.Currency);
                        return true;
                    }
                    catch (Exception)
                    {
                        UMD.ShowGuiMessageSTASafe_NOTHROW("The wage rate that you entered was not in a proper decimal format.");
                        return true;
                    }
                }
                else if (rateOnVOvertimePayTextBox.Text != null && rateOnVOvertimePayTextBox.Text.Count() != 0)
                {
                    try
                    {
                        Decimal.Parse(rateOnVOvertimePayTextBox.Text, NumberStyles.Currency);
                        return true;
                    }
                    catch (Exception)
                    {
                        UMD.ShowGuiMessageSTASafe_NOTHROW("The overtime rate that you entered was not in a proper decimal format.");
                        return true;
                    }
                }
            }
            return true;
        }
    }
}
